Imports System.IO
Imports System.Windows.Forms
Imports Vintasoft.Pdf
Imports Vintasoft.Pdf.Security

Namespace Pdf.Security
	Public Partial Class PasswordForm
		Inherits Form
		#Region "Constructors"

		Public Sub New()
			InitializeComponent()
			passwordTextBox.Focus()
		End Sub

		#End Region



		#Region "Properties"


		Private _filename As String
		Public Property Filename() As String
			Get
				Return _filename
			End Get
			Set
				_filename = value
				If _filename IsNot Nothing Then
					Text = String.Format("Password - {0}", Path.GetFileName(_filename))
				Else
					Text = "Password"
				End If
			End Set
		End Property


		Public ReadOnly Property Password() As String
			Get
				Return passwordTextBox.Text
			End Get
		End Property

		#End Region



		#Region "Methods"

		Private Sub buttonOk_Click(sender As Object, e As EventArgs)
			DialogResult = DialogResult.OK
		End Sub

		Private Sub buttonCancel_Click(sender As Object, e As EventArgs)
			DialogResult = DialogResult.Cancel
		End Sub

		Public Shared Function Authenticate(document As PdfDocument) As Boolean
			If document.IsEncrypted AndAlso document.AuthorizationResult = AuthorizationResult.IncorrectPassword Then
				While True
					Dim enterPasswordDialog As New PasswordForm()
					If enterPasswordDialog.ShowDialog() = DialogResult.OK Then
						If document.Authenticate(enterPasswordDialog.Password) = AuthorizationResult.IncorrectPassword Then
							MessageBox.Show("The password is incorrect.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
						Else
							Exit While
						End If
					Else
						Return False
					End If
				End While
			End If
			Return True
		End Function

		#End Region
	End Class
End Namespace
